#  Welcome python world
#  It's me Lucas
#  Please start your creation

from pptx import Presentation
from pptx.util import Cm
import pandas as pd
import xlwings as xw
import time
import os
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl


class Re_port:
    def __init__(self, path):
        mpl.rcParams["font.sans-serif"] = ["HeiTi TC"]  # 展示中文字体
        mpl.rcParams["axes.unicode_minus"] = False  # 处理负刻度值

        self.df = pd.read_csv(path, skiprows=[0, 2, 3, 4, 5, 6], header=0, dtype=str)
        print(self.df.columns)
        # 绘图元数据处理
        self.df.dropna(subset=['Gyro_Offset X'], inplace=True)
        self.df['Gyro_Offset X'] = self.df['Gyro_Offset X'].astype(float)
        # 排序处理，只取第一次出现的时间
        self.df['uut_start'] = self.df['uut_start'].astype('datetime64[ns]')
        self.df = self.df.sort_values(by='uut_start').drop_duplicates(subset=['masked_sn', 'station_id'], keep='first')
        # 准备图形索引，共四列，join取得一新列，为plt.table做数据准备
        self.indexes = ['product_code', 'site_name', 'test_result', 'software_version']
        self.df['plot_data'] = self.df[self.indexes].apply(lambda x: '_by_'.join(x.values.astype(str)), axis=1)
        self.df.sort_values(by=self.indexes, inplace=True)



    def plot(self):
        plt.subplots_adjust(left=0.11, right=0.95, top=0.925, bottom=0.17)
        sns.stripplot(data=self.df, x='plot_data', y='Gyro_Offset X', jitter=True, hue=None, color='red', size=2,
                      linewidth=0.2)
        sns.boxplot(data=self.df, x='plot_data', y='Gyro_Offset X', color='white', fliersize=0.4)
        self.plot_index_table()
        plt.axhline(y=-4.3, xmin=0, xmax=1, color='red', ls=':', alpha=0.8)
        plt.axhline(y=4.3, xmin=0, xmax=1, color='red', ls=':', alpha=0.8)
        plt.text(x=-1.4, y=4.3, s='max_spec', fontsize=9, color='red')
        plt.text(x=-1.4, y=-4.3, s='min_spec', fontsize=9, color='red')
        plt.title('象限_Scatter')

        plt.xlabel('')
        plt.xticks([])
        # plt.show()
        plt.savefig('one.png', dpi=1200)

        prs = Presentation()

        # 使用第七个版式
        black_slide_layout = prs.slide_layouts[5]
        slide = prs.slides.add_slide(black_slide_layout)
        print('')
        left = top = Cm(3)
        pic = slide.shapes.add_picture("one.png", left, top)

        prs.save("添加图片2.pptx")

    def plot_index_table(self):
        for index in range(len(self.indexes)):
            i = 0
            data = ['_by_'.join(x.split('_by_')[:index + 1]) for x in self.df['plot_data'].unique()]
            unique_key = []
            print(data)
            for _ in data:
                if _ not in unique_key:
                    unique_key.append(_)
            for val in unique_key:
                ttl_len = len(data)
                the_table = plt.table(cellText=[[val.split('_by_')[-1]]],
                                      cellLoc='center',
                                      loc='bottom',
                                      bbox=[i,
                                            -0.05 * len(self.indexes) + (0.05 * index),  # [xmin, ymin, width, height]
                                            data.count(val) / ttl_len,
                                            0.05])
                the_table.set_fontsize(8)
                i += data.count(val) / ttl_len





if __name__ == "__main__":
    start = time.time()
    path = '/Users/user/PycharmProjects/n-Xiang-boxplot_jitter_point/mocks/mock_data.csv'
    me = Re_port(path)
    me.plot()

    print("Please start your creation")
    print(f"此程序运行是时间为{round(time.time() - start, 2)}秒")
